package cn.yunyichina.scheduler.jobs.dao.register.impl;

import cn.yunyichina.scheduler.jobs.constant.Constant;
import cn.yunyichina.scheduler.jobs.dao.register.MedicalReserveRegisterTimeoutDao;
import cn.yunyichina.scheduler.jobs.entity.register.RegisterRecord;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by Lullaby on 2016/8/11.
 */
@Repository
public class MedicalReserveRegisterTimeoutDaoImpl implements MedicalReserveRegisterTimeoutDao {

    private static final Logger logger = LoggerFactory.getLogger(MedicalReserveRegisterTimeoutDaoImpl.class);

    private static final String REGISTER_RECORD_MAPPER = "RegisterRecordMapper";

    @Resource
    private ComboPooledDataSource dataSource;

    @Resource
    private SqlSession sqlSession;

    public List<RegisterRecord> getTimeoutMedicalReserveRegisterRecords() {
        return sqlSession.selectList(
                REGISTER_RECORD_MAPPER.concat(Constant.PERIOD_SEPARATOR).concat("getTimeoutMedicalReserveRegisterRecords")
        );
    }

    public int setMedicalRegisterRecordTimeout(List<Map<String, String>> paramsList, int status) {
        StringBuffer buffer = new StringBuffer();
        int[] count = new int[]{};
        try (Connection connection = dataSource.getConnection();
             PreparedStatement statement = connection.prepareStatement(buffer.toString())) {
            for (Map<String, String> map : paramsList) {
                buffer.append("UPDATE `").
                        append(map.get("tableName")).
                        append("` SET REG_STATUS = ").
                        append(status).append(" WHERE ID = '").
                        append(map.get("id")).
                        append("';");
                String sql = buffer.toString();
                statement.addBatch(sql);
                logger.info("Update SQL -> {}", sql);
                buffer.setLength(0);
            }
            count = statement.executeBatch();
        } catch (SQLException e) {
            logger.error("批量更新异常", e);
        }
        return count.length;
    }

}
